
package guice.boot.archive.container.model;

import guice.boot.archive.common.util.StringUtils;
import guice.boot.archive.container.registry.PluginServiceProvider;
import guice.boot.archive.container.service.ContainerHolder;
import guice.boot.archive.spi.model.Plugin;
import guice.boot.archive.spi.model.PluginRuntimeContext;
import guice.boot.archive.spi.registry.ServiceFilter;
import guice.boot.archive.spi.registry.ServiceReference;
import guice.boot.archive.spi.service.plugin.PluginManagerService;
import guice.boot.archive.spi.service.registry.RegistryService;

import java.util.List;
import java.util.Set;

/**
 * Standard Plugin Context Implement
 */
public class PluginRuntimeContextImpl implements PluginRuntimeContext {

    private Plugin plugin;

    private PluginManagerService pluginManagerService = ContainerHolder.getContainer()
            .getService(PluginManagerService.class);

    private RegistryService registryService = ContainerHolder.getContainer()
            .getService(RegistryService.class);

    public PluginRuntimeContextImpl(Plugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public Plugin getPlugin() {
        return plugin;
    }

    @Override
    public Plugin getPlugin(String pluginName) {
        return pluginManagerService.getPluginByName(pluginName);
    }

    @Override
    public <T> ServiceReference<T> publishService(Class<T> ifClass, T implObject) {
        return publishService(ifClass, implObject, StringUtils.EMPTY_STRING);
    }

    @Override
    public <T> ServiceReference<T> publishService(Class<T> ifClass, T implObject, String uniqueId) {
        return registryService.publishService(ifClass, implObject, uniqueId,
                new PluginServiceProvider(plugin));
    }

    @Override
    public <T> ServiceReference<T> referenceService(Class<T> ifClass) {
        return referenceService(ifClass, StringUtils.EMPTY_STRING);
    }

    @Override
    @SuppressWarnings("unchecked")
    public <T> ServiceReference<T> referenceService(Class<T> ifClass, String uniqueId) {
        return registryService.referenceService(ifClass, uniqueId);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<ServiceReference> referenceServices(ServiceFilter serviceFilter) {
        return registryService.referenceServices(serviceFilter);
    }

    @Override
    public Set<String> getPluginNames() {
        return pluginManagerService.getAllPluginNames();
    }

    @Override
    public ClassLoader getClassLoader() {
        return plugin.getClassLoader();
    }
}